package com.base.data.elasticsearch.util.gson;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.base.data.elasticsearch.util.BaseDateUtil;

import java.io.IOException;
import java.util.Date;

public class JacksonDefaultSerializerDate extends JsonSerializer<Date> implements ContextualSerializer {

    private String pattern = BaseDateUtil.DEFAULT_TIME_PATTER;

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        try {
            jsonGenerator.writeString(BaseDateUtil.format(date, pattern));
        } catch (Exception e) {
            jsonGenerator.writeString(String.valueOf(date.getTime()));
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        AnnotationMap annotated = beanProperty.getMember().getAllAnnotations();

        JsonFormat jsonFormat = annotated.get(JsonFormat.class);
        if (jsonFormat != null && jsonFormat.pattern() != null) {
            pattern = jsonFormat.pattern();
        }
        return this;
    }


}
